import { useDebugValue, useRef, useState } from 'react';
import { useCall } from '.';

function useSet(defaultValue, asArray = false) {
  const [value, setValue] = useState(new Set(defaultValue ?? []));
  const add = useCall((element) => setValue((prev) => new Set(prev.add(element))));
  const remove = useCall((element) => setValue((prev) => (prev.delete(element), new Set(prev))));
  const clear = useCall(() => setValue(new Set()));
  const set = useCall((values) => setValue(new Set(values)));

  useDebugValue(value);
  return [asArray ? Array.from(value) : value, useRef({ add, remove, clear, set }).current];
}

export default useSet;
